import { addAccountAct, getAccountAct, updateAccountAct } from '@/redux/actions/account';
import { ReducersType } from '@/redux/store';
import { Space, Table, Input, Button, TablePaginationConfig, Modal, Form, Select, Radio, message } from 'antd';
import { useEffect, useState, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { SearchOutlined, PlusOutlined, BarChartOutlined } from '@ant-design/icons';
import "./index.less"
import { handlerBread } from '@/redux/actions';


const { Column } = Table;

const BreadData: breadType[] = [
    {
        label: "综合案例",
        icon: <BarChartOutlined />,
        herf: ''
    },
    {
        label: "账号管理",
        icon: undefined,
        herf: ''
    }
]

const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
};


const validateMessages = {
    required: "'${label}' 是必填字段",
    // ...
};

const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
}

let id: string;

let pageData = {
    page: 1,
    pageSize: 10
}

export default function Form1() {
    const dispatch = useDispatch()
    const AccountData: accountType = useSelector((state: ReducersType) => {
        return state.countReducer
    })
    const initPage = () => {
        pageData = {
            page: 1,
            pageSize: 10
        }
        setConfig({ ...pageConfig, pageSize: 10 , current: 1})
    }
    let saveTime = useRef<TablePaginationConfig>()
//     let PageData = useRef({
//     page: 1,
//     pageSize: 10
// })


    //账号列表展示
    const [loading, setLoading] = useState(true)
    const [title, setTitle] = useState("添加账号")
    const handlerAccountList = (name = '') => {
        dispatch(getAccountAct({ ...pageData, name })).then((res: any) => {
            // console.log(pageConfig);
            setConfig({ ...saveTime.current, total: res.count })
            setLoading(false)
        })
    }

    useEffect(() => {
        initPage()
        //获取账号数据
        handlerAccountList()
        //更改面包屑
        dispatch(handlerBread(BreadData))
       
    }, [])

    const PageChange = (page: number, pageSize: number) => {
        pageData.page = page
        pageData.pageSize = pageSize
        setConfig({ ...saveTime.current, pageSize, current: page })

        handlerAccountList()
    }
    let pageConfig: TablePaginationConfig = {
        position: ['bottomCenter'],
        // defaultCurrent: 1,
        total: 0,
        showTotal: (total: number) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        // defaultPageSize: 10,
        pageSize: 10,
        current: 1

    }

    let [config, setConfig] = useState((pageConfig))
    useEffect(() => {
        saveTime.current = config
    }, [config])

    //添加用户
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const [form] = Form.useForm();

    const [messageApi, contextHolder] = message.useMessage();

    const addAccount = () => {
        form.validateFields().then((values) => {
            setConfirmLoading(true);
            dispatch(addAccountAct(values)).then((res: string) => {
                if (res == "success") {
                    messageApi.success("添加用户成功")
                    handlerAccountList()
                    //清除表单数据
                    form.resetFields();
                    setIsModalOpen(false);
                    setConfirmLoading(false);
                } else {
                    messageApi.error("添加用户失败")
                    setConfirmLoading(false);
                }
            })
        }).catch((info) => {
            console.log('Validate Failed:', info);
            messageApi.error("添加用户失败")
            setConfirmLoading(false);
        });
    }

    const onFinish = () => {
        if (title == "添加账号") {
            addAccount()
        } else {
            updateAccount()
        }
    };
    const [value, setValue] = useState(1)

    //搜索列表
    const searchList = (e: any) => {
        initPage()
        handlerAccountList(e.target.value)
    }
    //编辑
    const handlerEdit = (e: accountDataType) => {
        form.setFieldsValue(e)
        setTitle("修改账号")
        //保存原始数据
        id = e.id
        setIsModalOpen(true);
    }

    const updateAccount = () => {

        form.validateFields().then((values) => {
            setConfirmLoading(true);
            dispatch(updateAccountAct({ ...values, id })).then((res: string) => {
                if (res == "success") {
                    messageApi.success("修改账号成功")
                    handlerAccountList()
                    //清除表单数据
                    form.resetFields();
                    setIsModalOpen(false);
                    setConfirmLoading(false);
                } else {
                    messageApi.error("修改账号失败")
                    setConfirmLoading(false);
                }
            })
        }).catch((info) => {
            console.log('Validate Failed:', info);
            messageApi.error("修改账号失败")
            setConfirmLoading(false);
        });
    }

    const handlerStatus = (e: accountDataType) => {
        dispatch(updateAccountAct({ ...e, status: e.status == 1 ? 0 : 1 })).then((res: string) => {
            if (res == "success") {
                messageApi.success(`${e.status == 1 ? "禁用" : '启用'}账号成功`)
                handlerAccountList()
            } else {
                messageApi.error(`${e.status == 1 ? "禁用" : '启用'}账号失败`)
            }
        })
    }

    return (
        <div className="Form1">
            <div className='header flex_a_sb'>
                <Input size="middle" placeholder="请输入姓名" prefix={<SearchOutlined />} style={{ width: 250 }} onPressEnter={searchList} allowClear />
                <Button size="middle" type="primary" onClick={showModal} >＋添加账号</Button>
            </div>
            <Table dataSource={AccountData.accountData} loading={loading} pagination={config} rowKey={item => item.id}>
                <Column title="姓名" dataIndex="name" key="name" />
                <Column title="账号" dataIndex="username" key="username" />
                <Column title="手机号" dataIndex="phone" key="phone" />
                <Column title="状态" dataIndex="status" key="status" render={
                    (status: number) => (
                        <>
                            {status == 1 ? '正常' : '禁用'}
                        </>
                    )
                } />
                <Column
                    title="操作"
                    key="action"
                    render={(_: any, record: accountDataType) => (
                        <Space size="middle">
                            <a style={{ color: '#4d98fa' }} onClick={() => handlerEdit(record)}>编辑</a>
                            <span style={{ opacity: 0.2, color: "gray" }}>|</span>
                            <a style={{ color: record.id == '1' ? '#dee1e6' : 'red', cursor: record.id == '1' ? "not-allowed" : 'pointer' }} onClick={() => handlerStatus(record)}>{record.status == 1 ? "禁用" : '启用'}</a>
                        </Space>
                    )}
                />
            </Table>
            <Modal title={title} open={isModalOpen} onCancel={handleCancel} onOk={onFinish} destroyOnClose={true} confirmLoading={confirmLoading} afterClose={() => form.resetFields()} >
                <div className='Form'>
                    <Form {...layout} form={form} name="control-hooks" validateMessages={validateMessages} >
                        <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
                            <Input allowClear />
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
            {contextHolder}
        </div>
    )
}